package dao;



import com.mysql.jdbc.Connection;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {
    private static volatile DataSource dataSource=null;

    private static DataSource getDataSource() {
        if (dataSource == null) {
            synchronized (DBUtil.class) {
                if (dataSource == null) {
                    dataSource = new MysqlDataSource();
                    ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/Blog_System?useSSL=false&characterEncoding=utf8");
                    ((MysqlDataSource) dataSource).setUser("root");
                    ((MysqlDataSource) dataSource).setPassword("1113");
                }
            }
        }
        return dataSource;
    }
    //建立连接
    public static  Connection getConnection(){
        try{
            return (Connection) getDataSource().getConnection();
        }catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //与数据库断开连接
    public static void close(Connection connection, PreparedStatement statment, ResultSet resultSet)
    {
        if(resultSet!=null)
            try{
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        if(statment!=null)
            try{
                statment.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        if(connection!=null)
            try{
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
    }

















}
